package priorityqueue;

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.StreamSupport;

/**
 * @Author liangzai
 * @Description:
 */
public class TestHeap {
    public int[] elem = new int[10];
    public int size = 0;

    public void initHeap(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            elem[i] = arr[i];
            size++;
        }
    }

    public void createHeap(){
        for (int parent = (size-1-1)/2 ; parent >=0 ; parent--) {
            siftDown(parent,size);
        }
    }

    private void swap(int i,int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    public void siftDown(int parent,int useSize) {
        int child = parent*2+1;
        while(child<useSize){
            if(child+1 < useSize && elem[child]<elem[child+1]){
                child++;
            }
            if(elem[child] > elem[parent]){
                swap(child,parent);
            }
            parent = child;
            child = parent*2+1;
        }
    }

    public void showHeap(){
        for (int i = 0; i < size; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }

    private boolean isFull(){
        if(size == elem.length){
            return true;
        }
        return false;
    }
    
    public void offer(int val){
        if(isFull()){
            Arrays.copyOf(elem,elem.length*2);
        }
        size++;
        elem[size-1] = val;
        siftUp(size-1);
    }

    public void siftUp(int child){
        int parent = (child-1)/2;
        while(parent>=0){
            if(elem[child]>elem[parent]){
                swap(child,parent);
                child = parent;
                parent = (child-1)/2;
            }else{
                break;
            }
        }
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public int poll(){
        if(isEmpty()){
            return -1;
        }
        int val = elem[0];
        swap(0,size--);
        siftDown(0,size);
        return val;
    }

    public int peek(){
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }
}

